package com.wfs.common.wechat;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.wfs.common.wechat.util.HttpRequestProxyUtil;
import com.wfs.common.wechat.util.WeChatUrl;
import org.apache.log4j.Logger;
import org.weixin4j.Configuration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 赵飞
 * @version V1.0
 * @Title:
 * @Package ${PACKAGE_NAME}
 * @Description:
 * @date 2017/3/29
 */
public class WebAuthProxyServlet extends HttpServlet {

	private static Logger logger = Logger.getLogger(WebAuthProxyServlet.class);

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		StringBuilder outStr = new StringBuilder();
		//运营者开始进行公众号授权
		String code =request.getParameter("code");
		String state = request.getParameter("state");
		String appid = request.getParameter("appid");


		//获取用户openid
		String openId = getOpenIdByCode(appid,code);

		if (Configuration.isDebug()) {
			System.out.println("获得公众号授权code:" + code);
			System.out.println("目标跳转参数state" + state);
			System.out.println("授权公众号appid" + appid);
			System.out.println("访问者openId:" + openId);
		}

		outStr.append("code:"+code+";state:"+state+"appid:"+appid+"openid:"+openId+"\n");


		//获取用户基本信息

		outStr.append(getUserInfo(appid,openId));

		response.getWriter().write(outStr.toString());

	}

	/**
	 * 获取用户信息
	 */
	public static String getUserInfo(String appid,String openId)
	{
		String jsonStr;
		try {
			jsonStr = HttpRequestProxyUtil.executeHttpGet(WeChatUrl.getUserInfoUrl(appid,openId), null);
			logger.info(jsonStr);
			if(jsonStr!=null) return jsonStr;
		}
		catch (Exception e)
		{
			e.printStackTrace();
			logger.error("获取用户基本信息信息失败",e);
		}
		return null;
	}


	/**
	 * 通过code获取openId
	 * @param code
	 * @return  成功获取返回openId,否则返回null
	 */
	public static String getOpenIdByCode(String appid,String code)
	{
		String jsonResult=null;
		try {
			jsonResult = HttpRequestProxyUtil.executeHttpPost(WeChatUrl.getOpenIdByCodeUrl(appid,code), null);
			JsonParser jsonParser=new JsonParser();
			JsonObject jsonObject= jsonParser.parse(jsonResult).getAsJsonObject();
			if(jsonObject.has("openid"))
			{
				return jsonObject.get("openid").getAsString();
			}else{
				logger.info("获取openId失败，errCode:"+jsonResult);
			}
			return null;
		}
		catch (Exception e)
		{
			e.printStackTrace();
			logger.error("通过code:"+code+"获取openId信息失败",e);
		}
		return null;
	}
}
